<template>
  <el-dialog v-model="dialogVisible" width="500" title="添加企业" @open="getData">
    <el-form :model="form" label-width="auto">
      <el-form-item label="企业名称">
        <el-select v-model="form.enterpriseId" placeholder="请选择需要添加到企业">
          <el-option
            v-for="item in enterpriseOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="行业名称">
        <el-select v-model="form.industryId" placeholder="请选择行业">
          <el-option
            v-for="item in industryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">添加</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { getEnterpriseAll, getIndustryAll, addEnterpriseToIndustry } from '@/api/enterprise'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const industryOptions = ref([])
const enterpriseOptions = ref([])
const form = ref({
  industryId: '',
  enterpriseId: '',
})
const openDialog = () => {
  form.value.industryId = ''
  form.value.enterpriseId = ''
  dialogVisible.value = true
}

const getData = async () => {
  const res1 = await getEnterpriseAll()
  if (res1.status === 201 || res1.status === 200) {
    // 处理数据，获取每个企业的信息
    enterpriseOptions.value = res1.data.data.map((enterprise) => {
      return {
        label: enterprise.name,
        value: enterprise.id,
      }
    })
  } else {
    ElMessage.error(res1.data.data || '获取企业信息失败')
  }
  const res2 = await getIndustryAll()
  if (res2.status === 201 || res2.status === 200) {
    // 处理数据，获取每个行业的信息
    industryOptions.value = res2.data.data.industries.map((industry) => {
      return {
        label: industry.name,
        value: industry.id,
      }
    })
  } else {
    ElMessage.error(res2.data.data || '获取行业信息失败')
  }
}
const emit = defineEmits(['submit'])
const submitForm = async () => {
  if (form.value.industryId === '' || form.value.enterpriseId === '') {
    ElMessage.error('请选择行业和企业')
    return
  }
  const res = await addEnterpriseToIndustry(form.value)
  if (res.status === 200 || res.status === 201) {
    ElMessage.success('添加成功')
    emit('submit')
    closeDialog()
  } else {
    ElMessage.error(res.data.data || '系统繁忙，请稍后再试')
  }
}
// 关闭弹窗方法
const closeDialog = () => {
  dialogVisible.value = false
}

defineExpose({
  openDialog,
  closeDialog,
})
</script>

<style lang="scss" scoped>
.el-select {
  width: 300px;
}
</style>
